#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: DisNight
# Create: 2020-12-28
# ******************************************************************************/

from src.util.dnf_utils import dnf_info_src, find_what_requires
from src.change_bin2src import get_source_name

import os
import argparse
import logging

logging.getLogger().setLevel(logging.INFO)

def get_all_berequired(save_dir, src2bin_map, dir_path="old", repos=None):
    """
    get all installed requires 
    :return: list
    """
    required_list = []
    for src_name in src2bin_map:
        current_path = os.path.join(save_dir, src_name, dir_path)
        logging.info("get %s required list", src_name)
        with os.scandir(current_path) as dir_iter:
            for entry in dir_iter:
                if entry.is_file():
                    bin_name = entry.name.split(".rpm")[0]
                    temp_list = find_what_requires(bin_name, repos)
                    for required_bin_name in temp_list:
                        required_src_name = get_source_name(required_bin_name)
                        if not required_src_name and not required_src_name in src2bin_map:
                            required_list.append(required_bin_name)
    return list(set(required_list))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-l", "--cvelist", default="",
                        help="path of cve pkgs")
    parser.add_argument("-d", "--savedir", default="",
                        help="dir of download dir")
    args = parser.parse_args()
    cve_list = args.cvelist if args.cvelist else "./cve_pkgs"
    pkg_list = load_pkgname(cve_list)
    requires_list = find_all_requires(pkg_list)
    save_file(requires_list, os.path.join(args.savedir, "what_requires"))